python

您所在的位置:网站首页 百度智能云ai文字识别api key python

python

2024-06-04 07:33| 来源: 网络整理| 查看: 265

注:本博客中的代码实现来自百度问答:https://jingyan.baidu.com/article/c1a3101ef9131c9e646deb5c.html

代码运行环境:win10  python3.7

需要aip库,使用pip install baidu-aip即可

(1)目的

通过百度AipOcr库,来实现识别图片中的表格,并输出问表格文件。

(2)实现

仿照百度问答:https://jingyan.baidu.com/article/c1a3101ef9131c9e646deb5c.html,实现了以下代码:

1 # encoding: utf-8 2 import os 3 import sys 4 import requests 5 import time 6 import tkinter as tk 7 from tkinter import filedialog 8 from aip import AipOcr 9 10 # 定义常量 11 APP_ID = 'xxxxxx' 12 API_KEY = 'xxxxxxxxxxxxxxxxxxxxxx' 13 SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxx' 14 # 初始化AipFace对象 15 client = AipOcr(APP_ID, API_KEY, SECRET_KEY) 16 17 # 读取图片 18 def get_file_content(filePath): 19 with open(filePath, 'rb') as fp: 20 return fp.read() 21 22 23 #文件下载函数 24 def file_download(url, file_path): 25 r = requests.get(url) 26 with open(file_path, 'wb') as f: 27 f.write(r.content) 28 29 30 if __name__ == "__main__": 31 root = tk.Tk() 32 root.withdraw() 33 data_dir = filedialog.askdirectory(title='请选择图片文件夹') + '/' 34 result_dir = filedialog.askdirectory(title='请选择输出文件夹') + '/' 35 num = 0 36 for name in os.listdir(data_dir): 37 print ('{0} : {1} 正在处理:'.format(num+1, name.split('.')[0])) 38 image = get_file_content(os.path.join(data_dir, name)) 39 res = client.tableRecognitionAsync(image) 40 # print ("res:", res) 41 if 'error_code' in res.keys(): 42 print ('Error! error_code: ', res['error_code']) 43 sys.exit() 44 req_id = res['result'][0]['request_id'] #获取识别ID号 45 46 for count in range(1, 20): #OCR识别也需要一定时间,设定10秒内每隔1秒查询一次 47 res = client.getTableRecognitionResult(req_id) #通过ID获取表格文件XLS地址 48 print(res['result']['ret_msg']) 49 if res['result']['ret_msg'] == '已完成': 50 break #云端处理完毕,成功获取表格文件下载地址,跳出循环 51 else: 52 time.sleep(1) 53 54 url = res['result']['result_data'] 55 xls_name = name.split('.')[0] + '.xls' 56 file_download(url, os.path.join(result_dir, xls_name)) 57 num += 1 58 print ('{0} : {1} 下载完成。'.format(num, xls_name)) 59 time.sleep(1) (3)实现效果

识别的表格图片为:

实现的效果为(注:表格的格式人为调整过,但内容没人为修改):

 可以看出,识别的精度还是很高的,只有“Fellow”识别为了“Fel1low”。

(4)其它

百度智能云应用创建链接:https://console.bce.baidu.com/ai/?_=1585935093810#/ai/ocr/app/list,创建了一个应用之后,就可以获得APP_ID、API_KEY、SECRET_KEY。

百度智能云文字识别接口说明:https://cloud.baidu.com/doc/OCR/s/3k3h7yeqa。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3